import React from 'react';
import { Layout, Menu } from 'antd';
import { 
  DashboardOutlined, 
  UserOutlined, 
  TeamOutlined,
  ApartmentOutlined 
} from '@ant-design/icons';
import { history } from 'umi';
import './SideMenu.less';

const { Sider } = Layout;
const { SubMenu } = Menu;

/**
 * 侧边菜单组件
 * 包含多级菜单结构
 */
const SideMenu: React.FC = () => {
  // 菜单数据配置
  const menuItems = [
    {
      key: 'dashboard',
      icon: <DashboardOutlined />,
      label: '驾驶舱',
      path: '/dashboard'
    },
    {
      key: 'user',
      icon: <UserOutlined />,
      label: '用户管理',
      path: '/user'
    },
    {
      key: 'department',
      icon: <TeamOutlined />,
      label: '部门管理',
      path: '/department',
      children: [
        {
          key: 'department-list',
          icon: <ApartmentOutlined />,
          label: '部门列表',
          path: '/department/list'
        },
        {
          key: 'department-structure',
          icon: <ApartmentOutlined />,
          label: '组织架构',
          path: '/department/structure'
        }
      ]
    }
  ];

  /**
   * 渲染菜单项
   */
  const renderMenuItems = (items: any[]) => {
    return items.map(item => {
      if (item.children) {
        return (
          <SubMenu
            key={item.key}
            icon={item.icon}
            title={item.label}
          >
            {renderMenuItems(item.children)}
          </SubMenu>
        );
      }
      
      return (
        <Menu.Item key={item.key} icon={item.icon}>
          {item.label}
        </Menu.Item>
      );
    });
  };

  /**
   * 处理菜单点击
   */
  const handleMenuClick = ({ key }: { key: string }) => {
    // 根据菜单key找到对应的路由路径
    const findPathByKey = (items: any[], targetKey: string): string | undefined => {
      for (const item of items) {
        if (item.key === targetKey) {
          return item.path;
        }
        if (item.children) {
          const childPath = findPathByKey(item.children, targetKey);
          if (childPath) return childPath;
        }
      }
      return undefined;
    };

    const targetPath = findPathByKey(menuItems, key);
    if (targetPath) {
      // 使用umi的history API进行路由跳转
      history.push(targetPath);
    }
  };

  return (
    <Sider width={200} className="side-menu">
      <Menu
        mode="inline"
        defaultSelectedKeys={['dashboard']}
        defaultOpenKeys={['department']}
        style={{ height: '100%', borderRight: 0 }}
        onClick={handleMenuClick}
      >
        {renderMenuItems(menuItems)}
      </Menu>
    </Sider>
  );
};

export default SideMenu;